package ee.serge;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class FileHelper {

   public static List<KnapsackObject> read(String path) throws IOException {
      FileInputStream fstream = new FileInputStream(path);
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;
      List<KnapsackObject> list = new ArrayList<KnapsackObject>();
      System.out.println(br.readLine());
      while ((strLine = br.readLine()) != null) {
         String[] pair = strLine.split(" ");
         list.add(new KnapsackObject(Integer.valueOf(pair[0]), Integer.valueOf(pair[1])));
      }
      in.close();
      return list;
   }
   
   public static void write(String path, KnapsackState state) throws IOException {
      FileWriter fstream = new FileWriter(path);
      BufferedWriter out = new BufferedWriter(fstream);
      out.write(String.valueOf(state.getPrice()) + " " + String.valueOf(state.getWeight()) + "\n");
      for (KnapsackObject item : state.getObjectsTaken()) {
         out.write(String.valueOf(item.getPrice()) + " " + String.valueOf(item.getWeight()) + "\n");
      }
      out.close();
   }
   
}
